import logging
import random

from bs4 import BeautifulSoup
from django.db import transaction
from django.views.decorators.http import require_http_methods

from back.models import ReportInformation, ReportType, AutomaticPostComment, AutomaticCommentList, AutomaticAccountList
from utils.decorators import json_check, check_login, back_role_check
from user_app.models import AccountInfo
from utils.common_utils import json_response, Pagination, AccountManager
from forum.models import Topic, Comment, BoardTopic, TopicThumb, TopicFollow, Attachments, ActivityTopic
from utils.query_utils import delete_topic_common
from utils.time_util import now
from django.db.models import F

logger = logging.getLogger(__name__)
error_logger = logging.getLogger("error")


@check_login
@json_check
def post_report(request, json_data: dict):
    """
        提交举报
    """
    account_id = request.session['account_id']
    topic_id = json_data.get('topic_id')
    comment_id = json_data.get('comment_id')
    category = json_data.get('category')
    reported_account_id = json_data.get('reported_account_id')
    report_type = json_data.get('report_type')
    report_content = json_data.get('report_content')

    tr = ReportInformation()
    if not reported_account_id:
        return json_response({"code": 1000, "message": "举报用户ID不能为空"})
    if comment_id:
        if not Comment.objects.filter(category=category, id=comment_id).exists():
            return json_response({"code": 1000, "message": "评论不存在"})
        else:
            tr.comment_id = comment_id
            tr.comment_content = Comment.objects.get(id=comment_id).content
    elif category == 0 and topic_id:
        if not Topic.objects.filter(id=topic_id).exists():
            return json_response({"code": 1000, "message": "帖子不存在"})
        else:
            tr.topic_id = topic_id
            tr.topic_subject = Topic.objects.get(id=topic_id).subject
    tr.reported_account_id = reported_account_id
    tr.report_type = report_type
    tr.report_content = report_content
    tr.created_by_id = account_id
    tr.save()
    return json_response({"code": 0, "message": "举报成功"})


@back_role_check
def get_report_list(request):
    """
        后台获取举报信息列表
    """
    page = int(request.GET.get('page', "1"))
    per_page = int(request.GET.get("per_page", "10"))
    start_time = request.GET.get("start_time", '')
    end_time = request.GET.get("end_time", '')
    query = ReportInformation.objects
    if start_time and end_time:
        query = query.filter(created_on__range=(start_time, end_time))
    report_count = query.count()
    p = Pagination(page=page, per_page=per_page, total=report_count)
    report_list = query.order_by("-created_on")[p.offset:p.offset + per_page]
    result_list = []
    account_mg = AccountManager()
    for item in report_list:
        created_by_id = item.created_by_id
        create_account_info = account_mg.get_account_by_id(created_by_id)
        reported_account_id = item.reported_account_id
        report_account_info = account_mg.get_account_by_id(reported_account_id)
        tmp = {
            "id": item.id,
            "topic_id": item.topic_id,
            "comment_id": item.comment_id,
            "topic_subject": item.topic_subject,
            "comment_content": item.comment_content,
            "nick_name": create_account_info.nick_name,
            "avatar": create_account_info.avatar,
            "created_account_id": created_by_id,
            "created_time": item.created_on,
            "report_nick_name": report_account_info.nick_name,
            "report_type": ReportType.objects.get(id=item.report_type).type_name,
            "report_content": item.report_content,
            "review_type": item.get_review_type_display(),
            "review_content": item.review_content,
            "category": item.category,
        }
        result_list.append(tmp)
    return json_response({"code": 0, "message": "", "data": {"item": result_list, "page_info": p.dict}})


@back_role_check
@json_check
def review_report(request, json_data: dict):
    """
        处理举报
    """
    account_id = request.session['account_id']
    report_id = json_data.get('report_id')
    review_type = int(json_data.get('review_type'))
    content = json_data.get('content')
    if report_id:
        query = ReportInformation.objects.filter(id=report_id)
        if query:
            report_info: ReportInformation = query[0]
            if report_info.review_type != 0:
                return json_response({"code": 1000, "message": "举报信息已被处理过"})
            else:
                if review_type == 1:
                    pass
                elif review_type == 2:
                    if report_info.topic_id:
                        # 删帖
                        delete_topic_common(report_info.topic_id)
                    elif report_info.comment_id:
                        # 屏蔽评论
                        Comment.objects.filter(id=report_info.comment_id).update(content='!@#$%^&*()_+')
                elif review_type == 3:
                    # 用户禁言
                    AccountInfo.objects.filter(id=report_info.reported_account_id).update(is_allow_post=1)
                query.update(review_type=review_type, report_content=content, review_account_id=account_id, review_time=now())
                return json_response({"code": 0, "message": "处理成功"})
        else:
            return json_response({"code": 1000, "message": "举报信息不存在"})
    else:
        return json_response({"code": 1000, "message": "参数错误"})


@check_login
def get_report_type(request):
    """
        获取举报类型
    """
    result_list = []
    query = ReportType.objects.filter(enable=0).order_by('id')
    for item in query:
        tmp = {
            "id": item.id,
            "name": item.type_name
        }
        result_list.append(tmp)
    return json_response({"code": 0, "message": "", "data": {"item": result_list}})


@back_role_check
def get_brand_check_list(request):
    """
        品牌审核列表
    """
    page = int(request.GET.get('page', "1"))
    per_page = int(request.GET.get("per_page", "10"))
    start_time = request.GET.get("start_time", '')
    end_time = request.GET.get("end_time", '')
    query = BoardTopic.objects
    if start_time and end_time:
        query = query.filter(created_on__range=(start_time, end_time))
    brand_count = query.count()
    p = Pagination(page=page, per_page=per_page, total=brand_count)
    brand_list = query.order_by("-created_on")[p.offset:p.offset + per_page]
    result_list = []
    for item in brand_list:
        tmp = {
            "id": item.id,
            "subject": item.subject,
            "nick_name": item.account_info.nick_name,
            "avatar": item.account_info.avatar,
            "created_time": item.created_on,
            "check_status": item.check_status,
            "check_content": item.check_content
        }
        result_list.append(tmp)
    return json_response({"code": 0, "message": "", "data": {"item": result_list, "page_info": p.dict}})


@back_role_check
@json_check
def check_topic_brand(request, json_data: dict):
    """
        审核品牌贴
    """
    brand_id = json_data.get('brand_id')
    check_status = json_data.get('check_status')
    bt = BoardTopic.objects.get(id=brand_id)
    if bt.check_status != 0:
        return json_response({"code": 1000, "message": "已被处理过"})
    else:
        BoardTopic.objects.filter(id=brand_id).update(check_status=check_status)
        return json_response({"code": 0, "message": "处理成功"})


@back_role_check
def get_topic_list(request):
    """
        后台贴子信息列表
    """
    category = request.GET.get("category")
    search = request.GET.get("search")
    page = int(request.GET.get('page', "1"))
    per_page = int(request.GET.get("per_page", "10"))
    obj = None
    if category == '0':
        obj = Topic.objects
    elif category == '1':
        obj = ActivityTopic.objects
    elif category == '2':
        obj = BoardTopic.objects
    if obj:
        if search:
            obj = obj.filter(subject__contains=search)
        topic_count = obj.count()
        p = Pagination(page=page, per_page=per_page, total=topic_count)
        topic_list = obj.order_by("-level", "-created_on")[p.offset:p.offset + per_page]
        result_list = []
        for item in topic_list:
            tmp = {
                "id": item.id,
                "subject": item.subject,
                "numreplies": item.num_replies,
                "numthumb": item.num_thumb,
                "numviews": item.num_views,
                "hidden": item.hidden,
                "level": item.level,
                "account": item.account_info.nick_name,
                "accountid": item.account_info.id,
                "avatar": item.account_info.avatar,
                "is_automatic": AutomaticPostComment.objects.filter(category=category, topic_id=item.id).exists(),
            }
            result_list.append(tmp)
        return json_response({"code": 0, "message": "", "data": {"item": result_list, "page_info": p.dict}})
    else:
        return json_response({"code": 1000, "message": "参数错误"})


@back_role_check
def delete_topic(request):
    """
        后台管理员删帖
    """
    topic_id = request.GET.get("topic_id")
    category = request.GET.get("category")
    with transaction.atomic():
        save_id = transaction.savepoint()
        try:
            TopicThumb.objects.filter(topic_id=topic_id, category=category).delete()
            TopicFollow.objects.filter(follow_topic_id=topic_id, category=category).delete()
            Attachments.objects.filter(topic_id=topic_id, category=category).delete()
            Comment.objects.filter(topic_id=topic_id, category=category).delete()
            AutomaticPostComment.objects.filter(topic_id=topic_id, category=category).delete()
            if category == '0':
                Topic.objects.filter(id=topic_id).delete()
            elif category == '1':
                ActivityTopic.objects.filter(id=topic_id).delete()
            elif category == '2':
                BoardTopic.objects.filter(id=topic_id).delete()
        except Exception as e:
            error_logger.exception("back_view delete_topic have a  error ---->%s" % e.__str__())
            transaction.savepoint_rollback(save_id)
            return json_response({"code": 1000, "message": "删除失败，请稍后再试"})
        transaction.savepoint_commit(save_id)
        return json_response({"code": 0, "message": "删除成功"})


@back_role_check
def top_topic(request):
    """
        后台管理员置顶帖子
    """
    topic_id = request.GET.get("topic_id")
    category = request.GET.get("category")
    is_top = False
    obj = None
    if category == '0':
        obj = Topic.objects.filter(id=topic_id)
    elif category == '1':
        obj = ActivityTopic.objects.filter(id=topic_id)
    elif category == '2':
        obj = BoardTopic.objects.filter(id=topic_id)
    if obj:
        result_dict = {
            "flag": is_top
        }
        if obj[0].level == 0:
            result_dict['flag'] = True
            # 查询每个Topic表中Level的最大值
            current_level = obj.model.objects.values('level').order_by('-level').first().get('level', 0)
            obj.update(level=current_level + 1)
            return json_response({"code": 0, "message": "置顶成功", "data": result_dict})
        else:
            obj.update(level=0)
            return json_response({"code": 0, "message": "取消置顶", "data": result_dict})
    else:
        return json_response({"code": 1000, "message": "参数错误"})


@back_role_check
def hidden_topic(request):
    """
        后台管理员屏蔽帖子
    """
    topic_id = request.GET.get("topic_id")
    category = request.GET.get("category")
    is_top = False
    obj = None
    if category == '0':
        obj = Topic.objects.filter(id=topic_id)
    elif category == '1':
        obj = ActivityTopic.objects.filter(id=topic_id)
    elif category == '2':
        obj = BoardTopic.objects.filter(id=topic_id)
    if obj:
        result_dict = {
            "flag": is_top
        }
        if not obj[0].hidden:
            result_dict['flag'] = True
            obj.update(hidden=True)
            return json_response({"code": 0, "message": "屏蔽成功", "data": result_dict})
        else:
            obj.update(hidden=False)
            return json_response({"code": 0, "message": "取消屏蔽", "data": result_dict})
    else:
        return json_response({"code": 1000, "message": "参数错误"})


@back_role_check
def update_topic_thumb(request):
    """
        后台管理员修改点赞量
    """
    topic_id = request.GET.get("topic_id")
    category = request.GET.get("category")
    num_thumb = request.GET.get("num_thumb")
    obj = None
    if category == '0':
        obj = Topic.objects.filter(id=topic_id)
    elif category == '1':
        obj = ActivityTopic.objects.filter(id=topic_id)
    elif category == '2':
        obj = BoardTopic.objects.filter(id=topic_id)
    if obj and num_thumb:
        obj.update(num_thumb=num_thumb)
        return json_response({"code": 0, "message": "修改成功", "data": {'flag': True}})
    else:
        return json_response({"code": 1000, "message": "参数错误"})


@back_role_check
def update_topic_views(request):
    """
        后台管理员修改阅读量
    """
    topic_id = request.GET.get("topic_id")
    category = request.GET.get("category")
    num_views = request.GET.get("num_views")
    obj = None
    if category == '0':
        obj = Topic.objects.filter(id=topic_id)
    elif category == '1':
        obj = ActivityTopic.objects.filter(id=topic_id)
    elif category == '2':
        obj = BoardTopic.objects.filter(id=topic_id)
    if obj and num_views:
        obj.update(num_views=num_views)
        return json_response({"code": 0, "message": "修改成功", "data": {'flag': True}})
    else:
        return json_response({"code": 1000, "message": "参数错误"})


@check_login
def delete_comment(request):
    """
        删除评论接口，这里不需要管理员权限也可以删除(但仅限自己)
    """
    comment_id = request.GET.get("comment_id")
    if not comment_id:
        return json_response({"code": 1000, "message": "参数错误"})
    Comment.objects.filter(id=comment_id).update(content='+_)(*&^%$#@!')
    return json_response({"code": 0, "message": "删除成功"})


@require_http_methods(['GET'])
@back_role_check
def automatic_post_comment(request):
    """
        自动发评论
    """
    account_id = request.session['account_id']
    topic_id = request.GET.get("topic_id")
    category = request.GET.get("category")
    obj = None
    if category == '0':
        obj = Topic.objects.filter(id=topic_id)
    elif category == '1':
        obj = ActivityTopic.objects.filter(id=topic_id)
    elif category == '2':
        obj = BoardTopic.objects.filter(id=topic_id)
    if obj:
        if obj.exists():
            if AutomaticPostComment.objects.filter(topic_id=topic_id, category=category).exists():
                AutomaticPostComment.objects.filter(topic_id=topic_id, category=category).delete()
                return json_response({"code": 0, "message": "已关闭", "data": {"flag": False}})
            else:
                ap = AutomaticPostComment()
                ap.topic_id = topic_id
                ap.category = category
                ap.created_by_id = account_id
                ap.save()

                comment_list = AutomaticCommentList.objects.all().values_list('content', flat=True)
                account_list = AutomaticAccountList.objects.all().values_list('account_id', flat=True)
                content = comment_list[random.randint(0, len(comment_list) - 1)]
                script_account_id = account_list[random.randint(0, len(account_list) - 1)]
                cm = Comment()
                cm.topic_id = topic_id
                cm.content = content
                cm.category = category
                cm.is_manual = 1
                cm.created_by_id = script_account_id
                cm.created_on = now()
                cm.save()
                # # 修改Topic评论数
                if category == '0':
                    tpc = Topic.objects.get(id=topic_id)
                    tpc.num_replies = F('num_replies') + 1
                    tpc.save(update_fields=['num_replies'])
                elif category == '1':
                    tpc = ActivityTopic.objects.get(id=topic_id)
                    tpc.num_replies = F('num_replies') + 1
                    tpc.save(update_fields=['num_replies'])
                elif category == '2':
                    tpc = BoardTopic.objects.get(id=topic_id)
                    tpc.num_replies = F('num_replies') + 1
                    tpc.save(update_fields=['num_replies'])
                return json_response({"code": 0, "message": "已开启", "data": {"flag": True}})
        else:
            return json_response({"code": 1000, "message": "参数错误"})
    else:
        return json_response({"code": 1000, "message": "参数错误"})
